<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          :disabled="onlyAnonymous"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评分" prop="appraiseScore">
        <el-select v-model="queryParams.appraiseScore" placeholder="请选择评分" clearable style="width: 160px;">
          <el-option v-for="n in 5" :key="n" :label="n + '分'" :value="n" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价日期">
        <div class="date-range-inline">
          <el-date-picker clearable
            v-model="queryParams.appraiseTimeStart"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="开始日期">
          </el-date-picker>
          <span class="date-range-dash">-</span>
          <el-date-picker clearable
            v-model="queryParams.appraiseTimeEnd"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="结束日期">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="只看匿名">
        <el-switch v-model="onlyAnonymous" active-text="只看匿名" @change="handleOnlyAnonymousChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['zmhshop:appraise:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zmhshop:appraise:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zmhshop:appraise:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['zmhshop:appraise:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appraiseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名称" align="center" prop="userId" width="120">
        <template #default="scope">
          <span>{{ getUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsId" width="150">
        <template #default="scope">
          <span>{{ getGoodsName(scope.row.goodsId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评价内容" align="center" prop="appraiseContent" min-width="200" />
      <el-table-column label="评价分数" align="center" prop="appraiseScore" width="156">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-rate 
              v-model="scope.row.appraiseScore" 
              disabled 
              show-score 
              :max="5"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              score-template="{value}分"
              style="--el-rate-icon-size: 16px;"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否匿名" align="center" prop="isAnonymous" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isAnonymous ? 'info' : 'success'">
            {{ scope.row.isAnonymous ? '匿名' : '非匿名' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="回复状态" align="center" prop="replyStatus" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.replyStatus === 1 ? 'success' : 'warning'">
            {{ scope.row.replyStatus === 1 ? '已回复' : '未回复' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="appraiseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appraiseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="View" 
            @click="handleViewReply(scope.row)"
            :disabled="scope.row.replyStatus !== 1"
          >查看回复</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['zmhshop:appraise:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评价管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appraiseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评价内容" prop="appraiseContent">
          <el-input 
            v-model="form.appraiseContent" 
            type="textarea" 
            :rows="4"
            placeholder="请输入评价内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="评价分数" prop="appraiseScore">
          <el-rate 
            v-model="form.appraiseScore" 
            :max="5"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            show-score
            score-template="{value}分"
            style="--el-rate-icon-size: 20px;"
          />
        </el-form-item>
        <el-form-item label="评价图片(多张用逗号分隔)" prop="appraiseImg">
          <image-upload v-model="form.appraiseImg"/>
        </el-form-item>
        <!-- 新增：是否匿名 -->
        <el-form-item label="是否匿名" prop="isAnonymous">
          <el-switch 
            v-model="form.isAnonymous"
            :active-value="1"
            :inactive-value="0"
            active-text="匿名"
            inactive-text="非匿名"
          />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="商品ID" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="评价时间" prop="appraiseTime">
          <el-date-picker clearable
            v-model="form.appraiseTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择评价时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="父评价ID" prop="appraiseParentId">
          <el-input v-model="form.appraiseParentId" placeholder="请输入父评价ID" />
        </el-form-item>
        <el-form-item label="商家回复内容" prop="replyContent">
          <el-input v-model="form.replyContent" placeholder="请输入商家回复内容" />
        </el-form-item>
        <el-form-item label="商家回复时间" prop="replyTime">
          <el-date-picker clearable
            v-model="form.replyTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择商家回复时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看回复对话框（只读） -->
    <el-dialog title="查看回复" v-model="viewReplyOpen" width="600px" append-to-body destroy-on-close>
      <div class="reply-container">
        <div class="evaluation-content">
          <h4>评价内容：</h4>
          <div class="content-box">
            <p>{{ viewReplyRow.appraiseContent }}</p>
            <div class="evaluation-info">
              <span>评分：{{ viewReplyRow.appraiseScore }}分</span>
              <span>时间：{{ parseTime(viewReplyRow.appraiseTime, '{y}-{m}-{d}') }}</span>
            </div>
          </div>
        </div>
        <div class="reply-display">
          <h4>回复内容：</h4>
          <div class="reply-box">
            <p>{{ viewReplyRow.replyContent }}</p>
            <div class="reply-info">
              <span>回复时间：{{ parseTime(viewReplyRow.replyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewReplyOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AppraiseManage">
import { listAppraise, getAppraise, delAppraise, addAppraise, updateAppraise } from "@/api/zmhshop/appraise"
import { listUser, getUser } from "@/api/zmhshop/user"
import { getGood, listGood } from "@/api/lkshop/goods"

const { proxy } = getCurrentInstance()

const appraiseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 只看匿名
const onlyAnonymous = ref(false)

// 查看回复（只读）
const viewReplyOpen = ref(false)
const viewReplyRow = ref({})

// 用户和商品数据缓存
const userCache = ref({})
const goodsCache = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appraiseScore: null,
    userName: '',
    goodsName: '',
    userId: null,
    goodsId: null,
    orderId: null,
    appraiseTimeStart: null,
    appraiseTimeEnd: null,
    isAnonymous: null,
    replyStatus: null
  },
  rules: {
    appraiseContent: [
      { required: true, message: "评价内容不能为空", trigger: "blur" }
    ],
    appraiseScore: [
      { required: true, message: "评价分数(1-5)不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 获取用户名称
const getUserName = (userId) => {
  if (!userId) return '-'
  if (userCache.value[userId]) {
    return userCache.value[userId]
  }
  getUser(userId).then(response => {
    if (response.data) {
      userCache.value[userId] = response.data.userNickname || response.data.userAccount || `用户${userId}`
    }
  }).catch(() => {
    userCache.value[userId] = `用户${userId}`
  })
  return `用户${userId}`
}

// 获取商品名称
const getGoodsName = (goodsId) => {
  if (!goodsId) return '-'
  if (goodsCache.value[goodsId]) {
    return goodsCache.value[goodsId]
  }
  getGood(goodsId).then(response => {
    if (response.data) {
      goodsCache.value[goodsId] = response.data.goodsName || `商品${goodsId}`
    }
  }).catch(() => {
    goodsCache.value[goodsId] = `商品${goodsId}`
  })
  return `商品${goodsId}`
}

/** 查询评价管理列表 */
async function getList() {
  loading.value = true
  let sendParams = { ...queryParams.value }

  // 名称字段不传后端
  delete sendParams.userName
  delete sendParams.goodsName

  // 开启只看匿名
  if (onlyAnonymous.value) {
    sendParams.isAnonymous = 1
  }

  // 用户名称 -> 用户ID，并排除匿名（除非只看匿名打开）
  if (queryParams.value.userName && queryParams.value.userName.trim()) {
    try {
      const userResp = await listUser({ userNickname: queryParams.value.userName.trim() })
      const users = userResp.rows || []
      if (users.length === 0) {
        appraiseList.value = []
        total.value = 0
        loading.value = false
        return
      }
      sendParams.userId = users[0].userId
      if (!onlyAnonymous.value) {
        sendParams.isAnonymous = 0
      }
    } catch (e) {
      appraiseList.value = []
      total.value = 0
      loading.value = false
      return
    }
  }

  // 商品名称 -> 商品ID
  if (queryParams.value.goodsName && queryParams.value.goodsName.trim()) {
    try {
      const goodsResp = await listGood({ goodsName: queryParams.value.goodsName.trim() })
      const goodsList = goodsResp.rows || []
      if (goodsList.length === 0) {
        appraiseList.value = []
        total.value = 0
        loading.value = false
        return
      }
      sendParams.goodsId = goodsList[0].goodsId || goodsList[0].id
    } catch (e) {
      appraiseList.value = []
      total.value = 0
      loading.value = false
      return
    }
  }

  // 查询后端
  const resp = await listAppraise(sendParams)
  let rows = resp.rows || []

  // 前端时间段过滤（兼容后端未实现）
  if (queryParams.value.appraiseTimeStart || queryParams.value.appraiseTimeEnd) {
    const start = queryParams.value.appraiseTimeStart ? new Date(queryParams.value.appraiseTimeStart).getTime() : null
    const end = queryParams.value.appraiseTimeEnd ? new Date(queryParams.value.appraiseTimeEnd).getTime() + 24*60*60*1000 - 1 : null
    rows = rows.filter(item => {
      const t = item.appraiseTime ? new Date(item.appraiseTime).getTime() : null
      if (!t) return false
      if (start && t < start) return false
      if (end && t > end) return false
      return true
    })
  }

  appraiseList.value = rows
  total.value = resp.total
  loading.value = false

  // 预加载名称
  appraiseList.value.forEach(item => {
    if (item.userId && !userCache.value[item.userId]) {
      getUserName(item.userId)
    }
    if (item.goodsId && !goodsCache.value[item.goodsId]) {
      getGoodsName(item.goodsId)
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    appraiseId: null,
    appraiseContent: null,
    appraiseImg: null,
    appraiseScore: null,
    userId: null,
    goodsId: null,
    orderId: null,
    appraiseTime: null,
    appraiseParentId: null,
    isAnonymous: null,
    replyContent: null,
    replyTime: null,
    replyStatus: null
  }
  proxy.resetForm("appraiseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.userName = ''
  queryParams.value.goodsName = ''
  queryParams.value.userId = null
  queryParams.value.goodsId = null
  queryParams.value.appraiseScore = null
  queryParams.value.appraiseTimeStart = null
  queryParams.value.appraiseTimeEnd = null
  onlyAnonymous.value = false
  handleQuery()
}

function handleOnlyAnonymousChange() {
  if (onlyAnonymous.value) {
    queryParams.value.userName = ''
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.appraiseId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加评价管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _appraiseId = row.appraiseId || ids.value
  getAppraise(_appraiseId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改评价管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appraiseRef"].validate(valid => {
    if (valid) {
      if (form.value.appraiseId != null) {
        updateAppraise(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAppraise(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _appraiseIds = row.appraiseId || ids.value
  proxy.$modal.confirm('是否确认删除评价管理编号为"' + _appraiseIds + '"的数据项？').then(function() {
    return delAppraise(_appraiseIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/zmhshop/appraise/export', {
    ...queryParams.value
  }, `appraise_${new Date().getTime()}.xlsx`)
}

function handleViewReply(row) {
  if (row.replyStatus !== 1) return
  viewReplyRow.value = { ...row }
  viewReplyOpen.value = true
}

getList()
</script>

<style scoped>
.date-range-inline {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
.date-range-dash {
  color: #909399;
  padding: 0 4px;
}

/* 复用 index.vue 的展示样式 */
.reply-container { padding: 20px 0; }
.evaluation-content { margin-bottom: 30px; }
.evaluation-content h4, .reply-display h4 { margin: 0 0 15px 0; color: #303133; font-size: 16px; }
.content-box { background: #f5f7fa; border-radius: 8px; padding: 20px; border-left: 4px solid #409eff; }
.content-box p { margin: 0 0 15px 0; color: #606266; line-height: 1.6; font-size: 14px; }
.evaluation-info { display: flex; gap: 20px; color: #909399; font-size: 12px; }
.reply-box { background: #f0f9ff; border-radius: 8px; padding: 20px; border-left: 4px solid #67c23a; }
.reply-box p { margin: 0 0 15px 0; color: #606266; line-height: 1.6; font-size: 14px; }
.reply-info { color: #909399; font-size: 12px; }
</style>